﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DevelopStudio.Basic;
using System.Collections;
using System.Collections.Generic;
using CommonManage = DevelopStudio.Common.Manage;
using DevelopStudio.Control.FormPage;

namespace DevelopStudio
{
    public partial class MainForm : Form
    {
        private int listControlViewCodeReviewHeight = 0;

        private bool initialized = false;

        private bool bForceClose = false;

        private List<ChangelistInfo> codeReviewChangelist;

        public MainForm()
        {
            InitializeComponent();

            this.listControlViewCodeReviewHeight = this.listControlViewCodeReview.Height;

            this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
            this.UpdateStyles();
        }

        private void RefreshMainPanel()
        {
            if (string.IsNullOrEmpty(Utility.Settings.Redmine.BasicInfo.BaseUrl) == true ||
                Utility.Settings.WorkingCopies.Count == 0)
            {
                MessageBox.Show(Properties.Resources.WarningFillSettings, this.Text);
                return;
            }

            OnSettingBeforeLoad();

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.RunWorkerAsync();
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if (worker != null)
            {
                worker.Dispose();
            }

            this.loadingProgress1.SendToBack();
            this.loadingProgress1.Visible = false;
            this.loadingProgress1.Stop();

            #region listControlViewCodeReview

            //this.listControlViewCodeReview.RemoveAll();

            if (this.codeReviewChangelist != null)
            {
                foreach (ChangelistInfo changelistInfo in this.codeReviewChangelist)
                {
                    if (changelistInfo.Status != (int)AppEnum.ChangelistStatus.Disabled &&
                        changelistInfo.Displayed == true)
                    {
                        CodeReviewPlatform workPlatform = new CodeReviewPlatform()
                        {
                            ChangelistInfo = changelistInfo
                        };

                        this.listControlViewCodeReview.Add(workPlatform);
                    }
                }
            }

            #endregion

            #region listControlViewWorkPlatform

            //this.listControlViewWorkPlatform.RemoveAll();

            foreach (WorkingCopyInfo copyInfo in Utility.Settings.WorkingCopies)
            {
                foreach (ChangelistInfo changelistInfo in copyInfo.ChangelistInfos)
                {
                    if (changelistInfo.Status != (int)AppEnum.ChangelistStatus.Disabled &&
                        changelistInfo.Displayed == true)
                    {
                        WorkPlatform workPlatform = new WorkPlatform()
                        {
                            ChangelistInfo = changelistInfo
                        };

                        if (changelistInfo.BugInfos.Count == 0)
                        {
                            workPlatform.ExpandBugBar = false;
                        }
                        else
                        {
                            workPlatform.ExpandBugBar = true;
                        }

                        this.listControlViewWorkPlatform.Add(workPlatform);
                    }
                }
            }

            #endregion

            OnSettingAfterLoad();

            this.initialized = true;
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                SearchBugs searchBugs = Utility.GetSearchBugs(Utility.Settings.MyInfo.ID);

                this.LoadCodeReview(searchBugs);

                foreach (WorkingCopyInfo var in Utility.Settings.WorkingCopies)
                {
                    Utility.GetAllChangeLists(var);
                    Utility.UpdateAllLocalWorkingCopyBugs(var, searchBugs);
                }

                Utility.SaveEnvironmentSettings();
            }
            catch(Exception ex)
            {
                this.Invoke(new Action(() => { MessageBox.Show(Utility.TraceException(ex)); }));
            }
        }

        private void LoadCodeReview(SearchBugs searchBugs)
        {
            codeReviewChangelist = Utility.LoadCodeReviewChangelist(searchBugs);
        }

        private void LaunchSettingsForm()
        {
            bool refresh = false;
            using (SettingsForm frm = new SettingsForm())
            {
                frm.InitializePageControl();
                frm.ShowDialog();
                refresh = frm.SettingChanged;
            }

            if (refresh == true)
            {
                this.RefreshMainPanel();
            }
        }

        #region Form Event

        private void buttonItemSettings_Click(object sender, EventArgs e)
        {
            try
            {
                this.LaunchSettingsForm();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Utility.TraceException(ex), this.Text);
                return;
            }
        }

        private void buttonItemExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                this.RefreshMainPanel();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Utility.TraceException(ex), this.Text);
                return;
            }
        }

        private void OnSettingBeforeLoad()
        {
            this.Enabled = false;
            this.expandableSplitterCodeReviewPlatform.Expanded = false;
            this.expandableSplitterWorkPlatform.Expanded = false;
            this.listControlViewCodeReview.RemoveAll();
            this.listControlViewWorkPlatform.RemoveAll();
            this.loadingProgress1.BringToFront();
            this.loadingProgress1.Visible = true;
            this.loadingProgress1.Update();
            this.loadingProgress1.Start();
        }

        private void OnSettingAfterLoad()
        {
            /*
            if (this.listControlViewCodeReview.Count > 0)
            {
                this.panelCodeReviewPlatform.Enabled = true;
                this.expandableSplitterCodeReviewPlatform.Expanded = true;
            }
            else
            {
                this.expandableSplitterCodeReviewPlatform.Expanded = false;
                this.panelCodeReviewPlatform.Enabled = false;
            }

            if (this.listControlViewWorkPlatform.Count > 0)
            {
                this.panelWorkPlatform.Enabled = true;
                this.expandableSplitterWorkPlatform.Expanded = true;
            }
            else
            {
                this.expandableSplitterWorkPlatform.Expanded = false;
                this.panelWorkPlatform.Enabled = false;
            }
             * */

            this.Enabled = true;
        }

        private void MainForm_Resize(object sender, System.EventArgs e)
        {
            this.listControlViewCodeReviewHeight = this.listControlViewCodeReview.Height;
        }

        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F5:
                    this.RefreshMainPanel();
                    break;
                case Keys.C:
                    break;
                case Keys.Space:
                    break;
            }

            if ((int)e.KeyData == ((int)Keys.Space + (int)Keys.Alt))   //Ctrl + Alt + 数字0 
            {

            }

            /*
            // 组合键

            if (e.KeyCode == Keys.F1 && e.Modifiers == Keys.Control)         //Ctrl+F1
            {
                btnShouYi_Click(this, EventArgs.Empty);
            }

            if ((int)e.Modifiers == ((int)Keys.Control + (int)Keys.Alt) && e.KeyCode == Keys.D0)   //Ctrl + Alt + 数字0 
            {

                MessageBox.Show("按下了Control + Alt + 0");

            }
             * */
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                this.Focus();

                Rectangle rect = new Rectangle((this.Size.Width - this.ClientSize.Width) / 2,
                    (this.Size.Height - this.ClientSize.Height + SystemInformation.CaptionHeight) / 2,
                    this.ClientRectangle.Width,
                    this.ClientRectangle.Height);
                this.Region = new Region(rect);

                this.ribbonControlMainMenu.Office2007ColorTable = (DevComponents.DotNetBar.Rendering.eOffice2007ColorScheme)Utility.Settings.View.Theme;
                this.comboBoxItemTheme.SelectedIndex = Utility.Settings.View.Theme;
                this.RefreshMainPanel();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Utility.TraceException(ex), this.Text);
                return;
            }
        }

        private void buttonItemRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                this.RefreshMainPanel();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Utility.TraceException(ex), this.Text);
                return;
            }
        }

        private void expandableSplitterCodeReviewPlatform_ExpandedChanged(object sender, DevComponents.DotNetBar.ExpandedChangeEventArgs e)
        {
            if (e.NewExpandedValue == false)
            {
                this.panelWorkPlatform.Top -= this.listControlViewCodeReviewHeight;
                this.panelWorkPlatform.Height += this.listControlViewCodeReviewHeight;
                this.panelCodeReviewPlatform.Height -= this.listControlViewCodeReviewHeight;
            }
            else
            {
                this.panelCodeReviewPlatform.Height += this.listControlViewCodeReviewHeight;
                this.panelWorkPlatform.Top += this.listControlViewCodeReviewHeight;
                this.panelWorkPlatform.Height -= this.listControlViewCodeReviewHeight;
            }

            this.panelCodeReviewPlatform.Update();
            this.panelWorkPlatform.Update();
            this.Update();
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            try
            {
                MouseEventArgs arg = e as MouseEventArgs;

                if (arg != null &&
                    arg.Button != MouseButtons.Right)
                {
                    this.ProcessShow();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Utility.TraceException(ex), this.Text);
                return;
            }
        }

        private void ProcessShow()
        {
            if (this.Visible == false ||
                this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;

                if (this.Focused == false)
                {
                    this.Focus();
                }
            }
            else if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.Focus();
            }
            else if (this.WindowState != FormWindowState.Minimized &&
                this.Focused == false)
            {
                this.Activate();
                this.Focus();
            }
            else
            {
                this.Hide();
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private void comboBoxItemTheme_SelectedIndexChanged(object sender, EventArgs e)
        {
            Utility.Settings.View.Theme = this.comboBoxItemTheme.SelectedIndex;
            this.ribbonControlMainMenu.Office2007ColorTable = (DevComponents.DotNetBar.Rendering.eOffice2007ColorScheme)Utility.Settings.View.Theme;
            Utility.SaveEnvironmentSettings();
            this.Update();
        }

        protected override void WndProc(ref Message m)
        {
            // 屏蔽掉最大化的事件相应
            if (m.Msg == 274)
            {
                if (m.WParam.ToInt32() == 61488)
                {
                    return;
                }
            }

            if (m.Msg == 16 &&
                this.bForceClose == false)
            {
                this.Visible = false;
                return;
            }

            base.WndProc(ref m);
        }

        #endregion

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.bForceClose = true;
            this.Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (About frm = new About())
            {
                frm.ShowDialog();
            }
        }

        private void buttonItemOpen_Click(object sender, EventArgs e)
        {
            try
            {
                string fileFullName = string.Empty;

                using (OpenFileDialog dlg = new OpenFileDialog())
                {
                    dlg.Filter = "(*.dsdiff)|*.dsdiff";
                    if (dlg.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    fileFullName = dlg.FileName;
                }

                string execFileFullPath = Path.Combine(Application.StartupPath, AppConst.DiffToolPath);

                Utility.ExecuteCmd(execFileFullPath, fileFullName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Utility.TraceException(ex), this.Text);
                return;
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                DirectoryInfo folderInfo = new DirectoryInfo(CommonManage.Utility.TempStudioPath);

                foreach (FileInfo fileInfo in folderInfo.GetFiles())
                {
                    try
                    {
                        fileInfo.Delete();
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (Exception)
            {
            }

            if (Directory.Exists(CommonManage.Utility.TempStudioPath) == false)
            {
                Directory.CreateDirectory(CommonManage.Utility.TempStudioPath);
            }
        }

        private void listControlViewCodeReview_ControlCountChanged(object sender, EventArgs e)
        {
            this.labelCodeReviewNum.Text = this.listControlViewCodeReview.Count.ToString();

            if (this.listControlViewCodeReview.Count <= 0)
            {
                this.expandableSplitterCodeReviewPlatform.Expanded = false;
                this.panelCodeReviewPlatform.Enabled = false;
            }
            else
            {
                this.panelCodeReviewPlatform.Enabled = true;
                this.expandableSplitterCodeReviewPlatform.Expanded = true;
            }
        }

        private void listControlViewWorkPlatform_ControlCountChanged(object sender, EventArgs e)
        {
            this.labelWorkPlatformNum.Text = this.listControlViewWorkPlatform.Count.ToString();

            if (this.listControlViewWorkPlatform.Count <= 0)
            {
                this.expandableSplitterWorkPlatform.Expanded = false;
                this.panelWorkPlatform.Enabled = false;
            }
            else
            {
                this.panelWorkPlatform.Enabled = true;
                this.expandableSplitterWorkPlatform.Expanded = true;
            }
        }

        private void buttonItemView_Click(object sender, EventArgs e)
        {
            using (CheckModificationSimpleForm dlg = new CheckModificationSimpleForm())
            {
                dlg.ShowDialog();
            }

            this.ProcessShow();
            this.RefreshMainPanel();
        }
    }
}
